package api

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"net/http"
	"os"
)

type testApi struct {
}

func (a testApi) FileUpload(c *gin.Context) {
	f, err := c.FormFile("fileKey")
	if err != nil {
		log.Error(err)
	}
	log.Debug(f.Filename)
	dst := "./" + f.Filename
	err = c.SaveUploadedFile(f, dst)
	if err != nil {
		log.Error(err)
	}

	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", f.Filename))
}

func (a testApi) MultipartFileUpload(c *gin.Context) {
	form, err := c.MultipartForm()
	if err != nil {
		log.Error(err)
	}
	files := form.File["upload[]"]
	for _, file := range files {
		log.Println(file.Filename)
		dst := "./" + file.Filename
		// 上传文件至指定目录
		c.SaveUploadedFile(file, dst)
	}
	c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
}

type TestForm struct {
	Username string `form:"username"`
	Age      int    `form:"age"`
	Honor    []string
}

func (a testApi) QueryParams(c *gin.Context) {
	var f TestForm
	if err := c.ShouldBindQuery(&f); err != nil {
		c.String(500, "参数不合法")
	}
	log.Debug(f)
	c.String(200, "ok")
}

func (a testApi) PostArray(c *gin.Context) {
	var f TestForm
	if err := c.ShouldBindJSON(&f); err != nil {
		c.String(500, "参数不合法")
	}
	log.Debug(f)
	c.String(200, "ok")
}

func (a testApi) TestErr(c *gin.Context) {
	fmt.Println(c.Request.Host)
	errors.New("aa")
	f, _ := os.Open("")
	f.WriteString("aa")

	//c.String(500, "err")
}
